//
//  VOLChangePasswordViewController.m
//  Volver
//
//  Created by administrator on 14-11-1.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLChangePasswordViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "VOLAppDelegate.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"


@interface VOLChangePasswordViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    MBProgressHUD *HUD;
}
@end

@implementation VOLChangePasswordViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    
    //设置标题
    self.title = @"修改密码";
    
    //添加返回按钮
    addBackButton();
    
    //设置输入框的安全属性，按钮的字体颜色
    self.passwordField.secureTextEntry = YES;
    self.checkPwdField.secureTextEntry = YES;
    
    [self.affirmButton setTitleColor:kThemeColor forState:UIControlStateNormal];
    [self.affirmButton setTitleColor:kBlackColor forState:UIControlStateHighlighted];
    
    //设置输入框的代理
    self.passwordField.delegate = self;
    self.checkPwdField.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 点击空白处收回键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - 按钮点击事件
#pragma mark 返回按钮
-(void)goBack:(id)sender{
    back;
}

#pragma mark 确认按钮点击事件
- (IBAction)changePassword:(id)sender {
    NSString *newPwd = self.passwordField.text;
    NSString *checkPwd = self.checkPwdField.text;
    
    //检测不能为空的项目
    NSMutableString *alertStr = [NSMutableString string];
    
    [alertStr appendString:@"请输入"];
    if ([newPwd isEqualToString:@""]) {
        [alertStr appendString:@"密码"];
    }
    if ([checkPwd isEqualToString:@""]) {
        if ([alertStr isEqualToString:@"请输入"]) {
            [alertStr appendString:@"确认密码"];
        }else{
            [alertStr appendString:@"和确认密码"];
        }
        
    }
    
    if (![alertStr isEqualToString:@"请输入"]) {
        [alertStr appendString:@"!"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:alertStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    //判断密码格式是否正确
    if (![self isValidPassword:newPwd]) {
        alertStr = [NSMutableString stringWithString:@"请输入6——22位以字母、数字、常用符号（除双引号）组成的密码！"];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:alertStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    //判断两次输入密码是否一致
    if (![newPwd isEqualToString:checkPwd]) {
        alertStr = [NSMutableString stringWithString:@"两次输入密码不一致"];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:alertStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    //如果都输入正确，判断格式是否正确
    
    //前面全部通过后，可以连网更改密码
    __block int result;
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        //执行修改操作
        result = [self submitPassword];
    } completionBlock:^{
        [HUD removeFromSuperview];
        HUD = nil;
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        HUD.mode = MBProgressHUDModeText;
        //判断修改结果
        switch (result) {
            case -2:
            case -1:
            case 0:
            {
                HUD.labelText = @"修改密码失败!";
            }
                break;
                
            case 1:
            {
                HUD.labelText = @"修改密码成功!";
                //本地保存新密码
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setValue:self.passwordField.text forKey:@"userPassword"];
            }
                break;
        }
        //显示
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
            if (result == 1) {
                //跳转
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
    }];
    
    
}
#pragma mark 提交密码
-(int)submitPassword{
    NSString *urlstr = [NSString stringWithFormat:@"%@user/changePassword",kHTTPHome];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //设置数据
    [request setPostValue:del.currentUser.userPhone forKey:@"userPhone"];
    //加密后修改
    [request setPostValue:[MD5 md5HexDigest:self.passwordField.text] forKey:@"userPassword"];
    
    //设置请求方式
    [request setRequestMethod:@"POST"];
    
    //发送同步请求
    [request startSynchronous];
    
    if (request.error != nil) {
        NSLog(@"请求失败");
        return -2;
    }
    
    
    NSData *data = [request responseData];
    
    //若没有数据返回，直接结束函数
    if (data == nil) {
        NSLog(@"submitPassword---data为空");
        return -1;
    }
    
    //修改聊天服务器上的密码
    [del updatepassword:del.currentUser.userPhone :[MD5 md5HexDigest:self.passwordField.text]];
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    return status;
}
#pragma mark - 验证密码是否是有效的
-(BOOL)isValidPassword:(NSString *)password{
    
    NSString *passwordRegex = @"^[a-zA-Z0-9/-:;()$&@,.?!'_#%]{6,12}+$";
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passwordRegex];
    return [passwordTest evaluateWithObject:password];
}

#pragma mark - UITextFieldDelegate方法
#pragma mark return键
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}
@end
